const app = {
    data() {
        return {
            // 当前页面模式
            page: "main",
            // 是否正在随机选择
            isChoosing: false,
            // 已选择的选项
            chosenOption: null,
            // 选项列表
            options: [
                {
                    id: 1,
                    name: "黄焖鸡米饭",
                    weight: 5,
                },
                {
                    id: 4,
                    name: "辣椒炒肉",
                    weight: 10,
                }
            ],
            // 最大选项ID
            maxOptionId: 4,
            // 定时器ID
            intervalId: null,
        };
    },
    components: {
        "icon-setting": ElementPlusIconsVue.Setting,
        "icon-close": ElementPlusIconsVue.CloseBold,
        "icon-add": ElementPlusIconsVue.Plus,
        "icon-delete": ElementPlusIconsVue.DeleteFilled,
    },
    methods: {
        // 切换至主页面
        switchToMainPage() {
            if (this.checkForm()) {
                this.page = "main";
                this.saveData();
                this.initDataBeforeStart();
            }
        },
        // 切换至设置页面
        switchToSettingPage() {
            this.page = "setting";
        },
        // 创建选项
        createOption() {
            this.maxOptionId++;
            const id = this.maxOptionId;
            this.options.push({
                id,
                name: "",
                weight: 1,
            });
        },
        // 删除选项
        deleteOption(id) {
            let index = null;
            for (let i = 0; i < this.options.length; i++) {
                if (this.options[i].id === id) {
                    index = i;
                    break;
                }
            }
            if (index !== null) {
                this.options.splice(index, 1);
            }
        },
        // 在开始之前初始化数据
        initDataBeforeStart() {
            /* 计算总权重 */

            let totalWeight = 0;
            for (const option of this.options) {
                totalWeight += option.weight;
            }

            /* 计算每个选项的概率区间 */

            // 已计算的概率和
            let probabilitySum = 0;
            for (let i = 0; i < this.options.length; i++) {
                const option = this.options[i];
                // 概率值
                option.probability = option.weight / totalWeight;
                // 概率区间起始点（闭）
                option.probabilityRangeStart = probabilitySum;
                // 累加概率和
                probabilitySum += option.probability;
                // 概率区间结束点（开）
                option.probabilityRangeEnd = i < this.options.length - 1 ? probabilitySum : 1;
            }

            /* 初始化数据 */

            this.isChoosing = false;
            this.chosenOption = null;
        },
        // 开始选择
        startChoose() {
            this.isChoosing = true;
            this.intervalId = setInterval(() => {
                // 生成一个[0, 1)范围的随机数
                const randomNumber = Math.random();
                // 查找此值所落在的区间
                for (const option of this.options) {
                    if (option.probabilityRangeStart <= randomNumber && randomNumber < option.probabilityRangeEnd) {
                        this.chosenOption = option;
                        break;
                    }
                }
            }, 10);
        },
        // 停止选择
        stopChoose() {
            clearInterval(this.intervalId);
            this.intervalId = null;
            this.isChoosing = false;
            console.log("选择的选项：", this.chosenOption);
        },
        // 保存数据
        saveData() {
            const optionsJson = JSON.stringify(this.options);
            localStorage.setItem("options", optionsJson);
        },
        // 载入数据
        loadData() {
            const optionsJson = localStorage.getItem("options");
            if (optionsJson) {
                this.options = JSON.parse(optionsJson);
                this.maxOptionId = 0;
                for (const option of this.options) {
                    if (option.id > this.maxOptionId) {
                        this.maxOptionId = option.id;
                    }
                }
            } else {
                this.options = [];
                this.maxOptionId = 0;
            }
        },
        // 检查表单
        checkForm() {
            let isValid = true;
            let errorMessage = null;
            for (const option of this.options) {
                if (!option.name) {
                    isValid = false;
                    errorMessage = "“去哪儿”不能为空！";
                    break;
                }

                if (!option.weight) {
                    isValid = false;
                    errorMessage = "“权重”不能为空！";
                    break;
                }
            }

            if (!isValid) {
                this.$message.error({
                    message: errorMessage,
                });
            }

            return isValid;
        },
    },
    mounted() {
        this.loadData();
    },
};

const vueApp = Vue.createApp(app);
vueApp.use(ElementPlus);
vueApp.mount("#app");
